package com.zyd.blog.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import javax.activation.MimetypesFileTypeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import com.zyd.blog.file.entity.VirtualFile;
import com.zyd.blog.file.util.FileUtil;
import com.zyd.blog.file.util.StreamUtil;

import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.OnProgressListener;

public class UcloudApiClient extends BaseApiClient {
	final static Logger logger = LoggerFactory.getLogger(UcloudApiClient.class);
	private String publickey  ;
	private String privatekey ;
	private String buketdoman ;
	private ObjectAuthorization OBJECT_AUTHORIZER;
	private ObjectConfig config;
	  private String url ;
	public UcloudApiClient() {
		super("ucloud");
	}

	public UcloudApiClient init( ) {
		 
		  OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
				this.publickey, this.privatekey);
		  config = new ObjectConfig(this.buketdoman);
		return this;
	}
	public UcloudApiClient init(String url,String publickey,String privatekey,String buketdoman) {
		this.url = url;
		if(publickey !=null && privatekey != null && buketdoman != null ) {
			this.publickey = publickey;
			this.privatekey = privatekey;
			this.buketdoman = buketdoman;
		}
		OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
				this.publickey, this.privatekey);
		config = new ObjectConfig(this.buketdoman);
		return this;
	}
 
	public VirtualFile uploadImgMulti(MultipartFile mfile) {
		String imgUrl = mfile.getOriginalFilename();
		Date startTime = new Date();
		try {
			InputStream fileHashIs = StreamUtil.clone(mfile.getInputStream());
			int index;
			
	        byte[] bytes = new byte[1024];
	       File file = File.createTempFile("temp",FileUtil.getSuffixByUrl(imgUrl));
	        mfile.transferTo(file.getAbsoluteFile());
	        Path path = Paths.get(file.getAbsolutePath());
	        String contentType = new MimetypesFileTypeMap().getContentType(file);
	        String fileName = file.getName();
	        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
	        if(suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")
	        		|| suffix.equalsIgnoreCase("gif") ) {
	        	
	        	contentType = "image/"+suffix;
	        }
	        logger.info(file+" -- "+contentType);
		    PutObjectResultBean response = UfileClient.object( OBJECT_AUTHORIZER, config)
		         .putObject(file, contentType)
		         .nameAs(file.getName())
		         .toBucket("rogan-pub")
		         .setOnProgressListener(new OnProgressListener() {
		              @Override
		              public void onProgress(long bytesWritten, long contentLength) {
		                  
		              }
		         })
		         .execute();
		    this.newFileName ="/"+ file.getName();
		    return new VirtualFile()
                    .setOriginalFileName( file.getName())
                    .setSuffix(this.suffix)
                    .setUploadStartTime(startTime)
                    .setUploadEndTime(new Date())
                    .setFilePath(this.newFileName)
                    .setFileHash(DigestUtils.md5DigestAsHex(fileHashIs))
                    .setFullFilePath(this.url + this.newFileName);
		} catch (UfileClientException e) {
		    e.printStackTrace();
		} catch (UfileServerException e) {
		    e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean removeFile(String key) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void check() {
		// TODO Auto-generated method stub

	}

	@Override
	public VirtualFile uploadImg(InputStream is, String key) {
		// TODO Auto-generated method stub
		return null;
	}

 

}
